package com.websever.core;

import com.websever.Http.HttpServletRequest;

import java.io.*;
import java.lang.management.GarbageCollectorMXBean;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/*
 线程任务
 负责与特定的客户端进行HTTP交互
 */
public class ClientHandler implements Runnable {
   private Socket socket;
   public ClientHandler(Socket socket){
       this.socket = socket;
   }

    public void run() {
        try {
           //解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            // 处理请求
            String path = request.getUri();

            // 发送响应 将。/webapps/myweb/idex.html
            File file = new File("./webapps"+path);
            OutputStream out = socket.getOutputStream();
            //发送状态行
            String line = "HTTP/1.1 200 OK";
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

           line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);
            out.write(10);

            //单独发送  结尾
            out.write(13);
            out.write(10);

            //发送响应文
            FileInputStream fis = new FileInputStream(file);
            int len;
            byte[] buf = new byte[1024*10];
            while ((len = fis.read(buf))!=-1){
                out.write(buf,0,len);
            }
            System.out.println("响应完成");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //响应后断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } }


}
